﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Srvtools;

namespace EEPManager
{
    public partial class frmSecurityMainOrgOverride : Form
    {

        DataTable tabOrg = null;
        DataTable OrgRoles = null;
        DataTable UsersList = null;
        List<string> lSql = null;

        public frmSecurityMainOrgOverride()
        {
            InitializeComponent();

            initOrgKind();
            initOrgRoles();
            initUsersList();

            infoComboBox1.SelectedValue = "";
            infoComboBox1.SelectedIndex = -1;
            textBox1.Text = "";

            lSql = new List<string>();

        }


        private void initOrgKind()
        {
            string sqlOrgKind = "select '' as ORG_KIND,'' as KIND_DESC union all select * from SYS_ORGKIND";
            DataTable tabOrgKind = CliUtils.ExecuteSql("GLModule", "cmdDDUse", sqlOrgKind, true, CliUtils.fCurrentProject).Tables[0];
            this.cmbOrgKind.DataSource = tabOrgKind;
            this.cmbOrgKind.ValueMember = "ORG_KIND";
            this.cmbOrgKind.DisplayMember = "KIND_DESC";
        }

        private void initOrgRoles()
        {
            OrgRoles = dsOrgRoles.RealDataSet.Tables[0];
        }


        private void initUsersList()
        {
            string Sql = "select USERGROUPS.*, USERS.USERNAME,GROUPS.GROUPName,GROUPS.DESCRIPTION from USERS " +
              " inner join USERGROUPS on USERGROUPS.USERID = USERS.USERID " +
              " inner join GROUPS on GROUPS.groupid=USERGROUPS.groupid " +
              " order by USERS.USERId asc";

            UsersList = CliUtils.ExecuteSql("GLModule", "cmdDDUse",
                       Sql, true, Srvtools.CliUtils.fCurrentProject).Tables[0];
        }

        private void cmbOrgKind_SelectedIndexChanged(object sender, EventArgs e)
        {
            initOrg(true);
        }

        private void initOrg(bool clearValues)
        {
            if (this.cmbOrgKind.SelectedValue.ToString() != "")
            {
                string sqlOrg = "select * from SYS_ORG where ORG_KIND='" + this.cmbOrgKind.SelectedValue + "'";
                tabOrg = CliUtils.ExecuteSql("GLModule", "cmdDDUse", sqlOrg, true, CliUtils.fCurrentProject).Tables[0];
                refreshOrgs(clearValues);
            }
        }


        private void refreshOrgs(bool clear)
        {
            List<string> lstOrgNo = new List<string>();
            List<string> lstOrgDesc = new List<string>();
            List<string> lstUpperOrg = new List<string>();
            this.tView.Nodes.Clear();
            foreach (DataRow row in tabOrg.Rows)
            {
                lstOrgNo.Add(row["ORG_NO"].ToString());
                lstOrgDesc.Add(row["ORG_DESC"].ToString());
                lstUpperOrg.Add(row["UPPER_ORG"] == null ? "" : row["UPPER_ORG"].ToString());
            }

            List<string> lstRootOrgNo = new List<string>();
            List<string> lstRootOrgDesc = new List<string>();
            List<string> lstChildOrgNo = new List<string>();
            List<string> lstChildOrgDesc = new List<string>();
            List<string> lstChildUpperOrg = new List<string>();
            for (int ix = 0; ix < lstOrgNo.Count; ix++)
            {
                // 以下判断为解决orgNo = upperOrg
                if (lstOrgNo[ix] != lstUpperOrg[ix])
                {
                    if (lstUpperOrg[ix] == string.Empty)
                    {
                        lstRootOrgNo.Add(lstOrgNo[ix]);
                        lstRootOrgDesc.Add(lstOrgDesc[ix]);
                    }
                    else
                    {
                        lstChildOrgNo.Add(lstOrgNo[ix]);
                        lstChildOrgDesc.Add(lstOrgDesc[ix]);
                        lstChildUpperOrg.Add(lstUpperOrg[ix]);
                    }
                }
            }
            int i = lstRootOrgNo.Count;
            TreeNode[] nodeMain = new TreeNode[i];
            for (int j = 0; j < i; j++)
            {
                nodeMain[j] = new TreeNode();
                tView.Nodes.Add(nodeMain[j]);
                nodeMain[j].Text = lstRootOrgDesc[j];
                nodeMain[j].Name = lstRootOrgNo[j];
                nodeMain[j].Tag = lstRootOrgNo[j];
            }
            int p = lstChildOrgNo.Count;
            TreeNode[] nodeChildren = new TreeNode[p];
            for (int q = 0; q < p; q++)
            {
                nodeChildren[q] = new TreeNode();
                nodeChildren[q].Text = lstChildOrgDesc[q];
                nodeChildren[q].Name = lstChildOrgNo[q];
                nodeChildren[q].Tag = lstChildOrgNo[q];
            }
            for (int an = 0; an < p; an++)
            {
                for (int x = 0; x < lstRootOrgNo.Count; x++)
                {
                    if (lstChildUpperOrg[an] == lstRootOrgNo[x])
                    {
                        nodeMain[x].Nodes.Add(nodeChildren[an]);
                    }
                }
                for (int s = 0; s < p; s++)
                {
                    if (lstChildUpperOrg[an].ToString() == lstChildOrgNo[s].ToString())
                    {
                        nodeChildren[s].Nodes.Add(nodeChildren[an]);

                        object id = nodeChildren[an].Name;
                        DataRow[] drs = OrgRoles.Select("ORG_NO='" + id + "'");
                        foreach (DataRow dr in drs)
                        {
                            TreeNode tn = new TreeNode();
                            tn.Name = dr["ROLE_ID"].ToString();
                            tn.Text = dr["ROLE_ID"].ToString() + " - " + dr["GROUPNAME"].ToString();
                            tn.ToolTipText = dr["ORG_NO"].ToString();
                            tn.Tag = "GROUP";
                            nodeChildren[an].Nodes.Add(tn);

                            DataRow[] drsUsers = UsersList.Select("GROUPID='" + tn.Name + "'");
                            foreach (DataRow drUser in drsUsers)
                            {
                                TreeNode tnUsers = new TreeNode();
                                tnUsers.Name = drUser["USERID"].ToString();
                                tnUsers.Text = drUser["USERID"].ToString() + " - " + drUser["USERNAME"].ToString();
                                tnUsers.ToolTipText = tn.Name;
                                tnUsers.Tag = "USER";
                                tn.Nodes.Add(tnUsers);
                            }
                        }
                    }
                }
            }
            this.tView.ExpandAll();
            //if (clear)
            //clearValues();
        }

        #region DragDrop
        private void tView_DragDrop(object sender, DragEventArgs e)
        {

            TreeNode NewNode;
            if (e.Data.GetDataPresent(typeof(TreeNode)))
            {
                Point pt = ((TreeView)sender).PointToClient(new Point(e.X, e.Y));

                TreeNode DestinationNode = ((TreeView)sender).GetNodeAt(pt);

                NewNode = (TreeNode)e.Data.GetData("System.Windows.Forms.TreeNode");

                if (DestinationNode != null && DestinationNode.Tag != null
                    && (DestinationNode.Tag.ToString() != "GROUP" && DestinationNode.Tag.ToString() != "USER") && NewNode.Tag.ToString() == "GROUP")
                {

                    try
                    {
                        //string Sql = "";
                        //Sql += "Delete From SYS_ORGROLES Where ORG_NO='" +
                        //    NewNode.ToolTipText + "' AND ROLE_ID='" + NewNode.Name + "' AND ORG_KIND='" + this.cmbOrgKind.SelectedValue + "' \r";

                        //Sql += "Insert Into SYS_ORGROLES Values('" + DestinationNode.Name + "','" + NewNode.Name + "','" + this.cmbOrgKind.SelectedValue + "') \r";


                        lSql.Add("Delete From SYS_ORGROLES Where ORG_NO='" +
                            NewNode.ToolTipText + "' AND ROLE_ID='" + NewNode.Name + "' AND ORG_KIND='" + this.cmbOrgKind.SelectedValue + "' \r");
                        lSql.Add("Insert Into SYS_ORGROLES Values('" + DestinationNode.Name + "','" + NewNode.Name + "','" + this.cmbOrgKind.SelectedValue + "') \r");

                        //Srvtools.CliUtils.ExecuteSql("GLModule", "cmdRefValUse",
                        //       Sql, true, Srvtools.CliUtils.fCurrentProject);

                        NewNode.ToolTipText = DestinationNode.Name;

                        DestinationNode.Nodes.Add((TreeNode)NewNode.Clone());

                        DestinationNode.Expand();

                        NewNode.Remove();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
                else if (DestinationNode != null && DestinationNode.Tag != null
                    && (DestinationNode.Tag.ToString() == "GROUP") && NewNode.Tag.ToString() == "USER")
                {
                    try
                    {
                        //string Sql = "";
                        //Sql += "Delete From USERGROUPS Where USERID='" +
                        //       NewNode.Name + "' AND GROUPID='" + NewNode.ToolTipText + "' \r";

                        //Sql += "Insert Into USERGROUPS Values('" + NewNode.Name + "','" + DestinationNode.Name + "') \r";

                        lSql.Add("Delete From USERGROUPS Where USERID='" +
                               NewNode.Name + "' AND GROUPID='" + NewNode.ToolTipText + "' \r");
                        lSql.Add("Insert Into USERGROUPS Values('" + NewNode.Name + "','" + DestinationNode.Name + "') \r");

                        //Srvtools.CliUtils.ExecuteSql("GLModule", "cmdRefValUse",
                        //       Sql, true, Srvtools.CliUtils.fCurrentProject);

                        NewNode.ToolTipText = DestinationNode.Name;

                        DestinationNode.Nodes.Add((TreeNode)NewNode.Clone());

                        DestinationNode.Expand();

                        NewNode.Remove();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }

            }

        }

        private void tView_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent("System.Windows.Forms.TreeNode"))
            {
                e.Effect = DragDropEffects.Move;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }

        }

        private void tView_ItemDrag(object sender, ItemDragEventArgs e)
        {
            TreeNode tn = e.Item as TreeNode;

            if (tn != null && tn.Tag != null && (tn.Tag.ToString() == "GROUP" || tn.Tag.ToString() == "USER"))
            {
                if ((e.Button == MouseButtons.Left) && (tn != null) && (tn.Parent != null))
                {
                    this.tView.DoDragDrop(tn, DragDropEffects.Copy | DragDropEffects.Move | DragDropEffects.Link);
                }
            }
        }
        #endregion

        private void button1_Click(object sender, EventArgs e)
        {
            int index = cmbOrgKind.SelectedIndex;
            object value = cmbOrgKind.SelectedValue;

            dsOrgRoles.SetWhere("1=1");
            initOrgKind();
            initOrgRoles();
            initUsersList();

            cmbOrgKind.SelectedIndex = index;
            cmbOrgKind.SelectedValue = value;

            cmbOrgKind_SelectedIndexChanged(null, null);

            lSql = new List<string>();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string sql = "";
            foreach (string s in lSql.ToArray())
            {
                sql += s;
            }
            if (sql != "")
            {
                if (MessageBox.Show("确认更新组织架构吗？", "ok", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    //MessageBox.Show(sql);
                    Srvtools.CliUtils.ExecuteSql("GLModule", "cmdRefValUse",
                           sql, true, Srvtools.CliUtils.fCurrentProject);
                    lSql = new List<string>();
                    MessageBox.Show("更新成功！");
                     
                }
            }
            else
            {
                MessageBox.Show("组织架构没有变更！");
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            string Filter = "";
            if (textBox1.Text != "")
            {
                Filter += " And GROUPNAME LIKE '%" + textBox1.Text.Trim() + "%' ";
            }
            if (infoComboBox1.SelectedIndex != -1)
            {
                Filter += " And ORG_NO LIKE '" + infoComboBox1.SelectedValue.ToString() + "%' ";
            }

            dsOrgRoles.SetWhere("1=1 " + Filter);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            infoComboBox1.SelectedValue = "";
            infoComboBox1.SelectedIndex = -1;
            textBox1.Text = "";
        }
    }
}
